package com.atguigu.function;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import java.util.stream.Stream;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.call;

public class UserDefinedFunction_Table {
    public static void main(String[] args) {
        Configuration configuration = new Configuration();
        configuration.setInteger("rest.port",10000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(configuration);
        env.setParallelism(2);

        DataStreamSource<String> waterSensorStream =
                env.fromElements("hello world", "hello hello", "hello atguigu atguigu");
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);

        //自定义table函数，相当于炸裂函数（ustf函数）
        Table table = tEnv.fromDataStream(waterSensorStream,$("line"));

        //1、注册表
        tEnv.createTemporaryView("word",table);

        //2、在内联中使用
        table
                //因为是制表函数，想象成将一个表和另一个表做join操作
                //.joinLateral(call(MySplit.class,$("line")))
                .leftOuterJoinLateral(call(MySplit.class,$("line")))
                .select($("line"),$("word"),$("len"))
                .execute().print();

        //3、在sql中使用自定义udtf函数
        //先注册函数
        tEnv.createTemporaryFunction("mysplit",MySplit.class);
        tEnv.sqlQuery("select " +
                " line, word, len" +
                " from word " +
                " join lateral table(mysplit(line)) on true ")
                .execute()
                .print();

    }

}
